package manager

import (
	"github.com/topfreegames/pitaya/logger"
	"github.com/topfreegames/pitaya/queue"
	"reflect"
	"sync"
)

var (
	StandManager *standManager
	standManagerOnce sync.Once
)

type standManager struct {
	BaseManager
	EventQueue    *queue.BaseQueue
	mapStandLogic map[int]StandLogic
}

const (
	StandLogicPower = 1 //玩家战斗力
	StandLogicGang = 2 //帮会战斗力
	StandLogicLevel = 3 //玩家等级
	StandLogicSmzt = 4 //镇妖台挑战层数
	StandLogicGem = 5 //宝石战斗力
	StandLogicFabao = 6 //法宝战斗力
	StandLogicSoul = 7 //元魂总评分
	StandLogicRide = 8 //坐骑战斗力
	StandLogicCharm = 9 //总魅力值
	StandLogicAchievement = 10 //总成就
	StandLogicAnswer = 11 //答题活动
	StandLogicGangHonor = 12 //帮会荣誉
	StandLogicNumber = StandLogicGangHonor + 1

	StandLogicForbid = 99 //禁止进榜

	MaxStandNum = 200 //最大排名数
	MsgStandNum = 100
)

func (p *standManager) Init()  {
	for _,logic := range p.mapStandLogic {
		err := logic.Init(logic)
		if err != nil {
			logger.Log.Errorf("[StandManager] Init failed,error:%s",err.Error())
		}
	}
}


func NewStandManager() *standManager {
	standManagerOnce.Do(func() {
		var event IStandEvent
		typ := reflect.TypeOf(event)

		StandManager = &standManager{
			EventQueue: queue.NewBaseQueue(typ),
			mapStandLogic: map[int]StandLogic{
				StandLogicPower: NewPowerStandLogic(),
				StandLogicFabao: NewFabaoStandLogic(),
				StandLogicForbid: NewForbidStandLogic(),
			},
		}
	})
	return StandManager
}

/**
添加一个事件
 */
func (p *standManager) AddEvent(event IStandEvent)  {
	p.EventQueue.Offer(event)
}

/**
定时执行
 */
func (p *standManager) Tick(now int64) error {
	p.processEvent()

	//todo:其他更新事件

	return nil
}

/**
处理消息
 */
func (p *standManager) processEvent()  {
	for ;p.EventQueue.Size() > 0; {
		e := p.EventQueue.Poll()
		if e != nil {
			err := e.Value.(IStandEvent).process()
			if err != nil {
				logger.Log.Errorf("[StandManager] processEvent failed,error:%s",err.Error())
			}
		}
	}
}

func (p *standManager) GetStandLogic(logicId int) StandLogic {
	return p.mapStandLogic[logicId]
}
